/**
 * 项目状态聚合
 */
define([
    "dojo/_base/declare",
    "gistech/widgets/normalDialog/NormalDialog",
    "dojo/text!./templates/Template.html",
    "dojo/_base/lang",
    "dojo/topic",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dojo/on",
    "dojo/_base/array",
    "dojo/_base/connect",
    "dojo/topic",
    "gistech/widgets/ClusterInfoWindow/ChartColumnarWidget",
    ],
    function(declare,NormalDialog,template,lang,Topic,style,domConstruct,on,array,eventconnect,topic,
    		ChartColumnarWidget){
        return declare([NormalDialog],{
        templateString:template,
        container:null,
        checkedTypes:null,
        targets:null,
        tempTargets:null,
        constructor:function (args) {
        	this.inherited(arguments);//这个可以不需要
        	this.map = args.map;
        	this.userPermission={
        			"data":ioc.map.userRoleData,
        			"condition":null,//FQMC in ('南海区','顺德区')
        			"city":{}//{"广州市":[]}
        	}
        	this.targets=[{xmjd:'核查项目' },{xmjd:'洽谈项目' },{xmjd:'获取项目' }];
        }, 	 
        	 
        postCreate:function(){
            this.init();
            this.addEvents();
            this.inherited(arguments);//存在继承的话这个就必须得要
        },
        //初始化
        init:function (){
        	 this._projTypeFormElmInit();
        },
        //添加事件
        addEvents:function(){
        	on(this.basicBufferSaveBtn,"click",lang.hitch(this,this._createChart));
        	//on(this.cleanColumnCLuster,"click",lang.hitch(this,this.cleanCluster));//清除
        	topic.subscribe("changeCluster", lang.hitch(this, this.changeClusterData));//地图区域变动时重新加载
        	//on(this.basicBufferResetBtn,"click",lang.hitch(this,this._resetBuffer));
        	
        },
        
        //初始化查询日期 
        _projTypeFormElmInit:function(){
			//debugger
        	var today=new Date();
        	this.endDate.value=today.toISOString().split('T')[0];
        	this.startDate.value=new Date(today.setMonth(today.getMonth()-1)).toISOString().split('T')[0];
			$("input:checkbox[name=projType]",this.domNode).each(function(i,item){
			    $(item).iCheck({
	                checkboxClass: 'icheckbox_flat-green',
	                radioClass: 'iradio_flat-green'
	            });
				   
			});
		},
		
		
		//聚合
		_createChart:function(){
			debugger;
        	ioc.map.cluster=true;
        	ioc.map.clusterType="project"
			
			if(ioc.map.ClusterMapLevel == null){
        		ioc.map.ClusterMapLevel = this.map.getLevel();
        		
            	//3级别以下省;4,5,6级别市 ; 7以上行政区
            	if(this.map.getLevel()<=3){
            		ioc.map.ClusterDimension="province"
            	}else if(this.map.getLevel()>=4 && this.map.getLevel()<=6){
            		ioc.map.ClusterDimension="city"
            	}else if(this.map.getLevel()>=7){
            		ioc.map.ClusterDimension="distinct"
            	}
        	}
        	
        	
        	if(this.map.getLevel()<=3){
        		mark="province"
        	}else if(this.map.getLevel()>=4 && this.map.getLevel()<=6){
        		mark="city"
        	}else if(this.map.getLevel()>=7){
        		mark="distinct"
        	}
        	ioc.map.ClusterMapLevel = this.map.getLevel() ; 
         
			
        	this.checkedTypes = dojo.query(".icheckbox_flat-green.checked",this.domNode).map(function(item){
				return dojo.query('input:checkbox[name=projType]',item)[0].value;
			});
        	
        	//聚合数据中的表名
        	projClusterPara=['SDDCGISPLATFORM.WYTZ_1'];
			
			if(this.startDate.value!=''&&this.endDate.value!=''&&this.startDate.value>this.endDate.value){
				alert("起始时间不能大于结束时间");
				return;
			}
			projClusterPara.push(this.startDate.value);
			projClusterPara.push(this.endDate.value);
			
			//查询详细信息时用到
			ioc.map.clusterProjectStartDate = this.startDate.value;
			ioc.map.clusterProjectEndDate = this.endDate.value;
			
			if(this.checkedTypes.length==0){
				alert("请选择项目进度类型");
			}else{
				// 非同一个维度时重新查询加载 
	    		var flag =null;
	    		if(mark == 'distinct' ){//  
	    			this.clustData(1,projClusterPara)
	        	}else if(mark == 'city'){//  
	        		this.clustData(2,projClusterPara)
	        	}else if(mark == 'province'){//  
	        		this.clustData(3,projClusterPara)
	        	}
				
			}
			
		},
		
		cleanCluster:function(){
        	ioc.map.cluster=false;//清除图层用
        	this.delPie();
        },
		
		clustData:function(flag,projClusterPara){
			
        	this.delPie();

        	if(ioc.map.shiQufeatures == undefined){
        		ioc.map.shiQufeatures = [];
        	}
    		var temp = this;
    		//后台处理数据
    		$.ajax({
					type:'post',
					url:'../client/service/clusterController/clusterProjTypesData',
					data:{
						projClusterPara:JSON.stringify(projClusterPara)
					},
					dataType:'json',
					success:function(response){
						 var projTypes = eval(response.result);
						 var act =eval(projTypes.act); //实际指标
						 var target = eval(projTypes.target); //计划指标[只统计了个数,需根据指标公式计算]
		    			 if(act!=null && act.length>0){
		    				 ioc.map.clusterData=temp.preDealData(act,target);
		    				 temp.initCluster(null,null,flag,temp);
		    			 }
					},
					error:function(response){
						 
					}
			});
			 
        },
        
        	preDealData:function(projTypes,monthTarget){
        		
        		var tempthis= this ;
        		var clusterDatas=[];
        		
        		projTypes.forEach(function(item){
        			var data=new Object();
        			data.REG=item.REG;//集团名称,已转换成广州市,东莞市......
        			data.REGTYPE=item.REGTYPE; //城市类型
        			
        			//集团负责人只能查看其集团下的数据
//        			if(ioc.map.companyName!='null'&&data.REG==ioc.map.companyName){
//            			item.XMJDTYPES.split(',').forEach(function(type){//项目阶段名称
//            				var xmjd=type.split('&')[0];
//            				//判断是否在查询的项目阶段中
//            				if($.inArray(xmjd,tempthis.checkedTypes)>-1){
//            					data[xmjd]=type.split('&')[1];
//            				}
//            			});
//            			clusterDatas.push(data);
//        			}else{
//        				if(ioc.map.userInfoData.isManager){//管理员
//                			item.XMJDTYPES.split(',').forEach(function(type){//项目阶段名称
//                				var xmjd=type.split('&')[0];
//                				//判断是否在查询的项目阶段中
//                				if($.inArray(xmjd,tempthis.checkedTypes)>-1){
//                					data[xmjd]=type.split('&')[1];
//                				}
//                			});
//                			clusterDatas.push(data);
//        				}
//        				
//        			}
        			//所有人都可以查看
        			item.XMJDTYPES.split(',').forEach(function(type){//项目阶段名称
        				var xmjd=type.split('&')[0];
        				//判断是否在查询的项目阶段中
        				if($.inArray(xmjd,tempthis.checkedTypes)>-1){
        					data[xmjd]=type.split('&')[1];
        				}
        			});
        			clusterDatas.push(data);

        		});
        		
        		
        		
        		//返回满足给定数组中回调函数中规定条件的元素组成的新数组
        		this.tempTargets = this.targets.filter(function(item){//选择的项目
        			return $.inArray(item.xmjd,tempthis.checkedTypes)>-1;
        		});
        		
        		
        		
        		//对计划指标进行处理
        		var result = new Array();
        		for(var i=0;i<monthTarget.length;i++){
        			var temp=monthTarget[i];	
        			
//        			//所有人可查看
//        			for(var j=0;j<this.tempTargets.length;j++){
//        				temp[this.tempTargets[j].xmjd]=temp['EMPMONTHNUM']*this.tempTargets[j].value;//给每一个项目指标计算
//				    }
        			//所有人可查看
        			for(var j=0;j<this.tempTargets.length;j++){        				
        				var typeTarget = temp['EMPMONTHNUM']; // 1-20,2-5 这种格式
        				if(typeTarget!=null || typeTarget!=''){
        					var types = typeTarget.split(',');
        					for(var s = 0;s<types.length;s++){
        						var detailType = types[s].split('-')[0];
        						var target = types[s].split('-')[1];
        						if(this.tempTargets[j].xmjd=='核查项目' && '1'== detailType){
        							temp[this.tempTargets[j].xmjd] = parseInt(target);
        						}else if(this.tempTargets[j].xmjd=='洽谈项目'&& '2' == detailType){
        							temp[this.tempTargets[j].xmjd] = parseInt(target);
        						}
        					}
        				}
				    }
        			
        			result.push(temp);
        			
        		}
        		 
        		 this.monthTarget=result;
        		
        		 return clusterDatas;
        		
        	},
		
          initCluster:function(queryTask,query,flag,temp){

	      	  if(queryTask==null){
	      		  if(ioc.map.ClusterDimension == 'city'){
	      			  this.dealWithData(ioc.map.shifeatures,flag,temp);
	      		  }else if(ioc.map.ClusterDimension == 'distinct'){
	      			  this.dealWithData(ioc.map.qufeatures,flag,temp);
	      		  }
	      	  }else{
	      		  if(flag==9){
	      			  queryTask.execute(query,lang.hitch(this,function(feaset){
	      				  ioc.map.shifeatures=feaset;
	      			  }));
	      		  }else if(flag==10){
	      			  queryTask.execute(query,lang.hitch(this,function(feaset){
	      				  ioc.map.qufeatures=feaset;
	      			  }));
	      		  }
	
	      	  }

          },

      
        dealWithData:function(feaset,flag,temp){
      	
			for(var i=0;i<feaset.length;i++){
				var fs = feaset[i];
	        	var tPoint = fs.point;
	        	var name = fs.name ; 
	        	var clusdata = ioc.map.clusterData;
	     		 if(clusdata.length>0){
	     			 for(var j=0;j<clusdata.length;j++){
	     				 var data = clusdata[j];
	     				 var dimensionName = "";
	     				 if(flag==1 || ioc.map.ClusterDimension == 'distinct'){
	     					dimensionName = data.REG
	     				 }else if(flag==2 || ioc.map.ClusterDimension == 'city'){
	     					dimensionName = data.REG
	     				 }else if(flag==3 || ioc.map.ClusterDimension == 'province' ){ 
	     					dimensionName = ""; //TODO 省
	     				 }
	     				  
	     				 if(name== dimensionName ){
	     					 var isCity = false;
	     					 var cityTarget =this.monthTarget.filter(function(item){
	     						 return item.CITY == dimensionName;
	     					 });
	     					   if(ioc.map.ClusterDimension=='city' && data.district==undefined)
	     						  isCity = true ; 
	     					   if( ioc.map.ClusterDimension=='city' && !isCity)
	     						  break
	     		        	   var chartWidget =  new ChartColumnarWidget({map:temp.map,clusterType:this.clusterType});
	     		        	   chartWidget.placeAt(temp.getLayer()).show(tPoint);
	     		        	   chartWidget.startup(dimensionName,data,this.tempTargets,cityTarget);
	     		        		   
	     				 }
	     			 }
	     		 }
			}
        },
        
      //比例尺变动时改变聚合
        changeClusterData:function(){
        	
        	if(!ioc.map.cluster){
        	  return;	
        	}
        	
        	if(ioc.map.clusterType !="project"){
        		return;	
        	}
        		
        	if(ioc.map.clusterData!=undefined && ioc.map.clusterData!=null)
            if(ioc.map.ClusterMapLevel!=this.map.getLevel()){
            	this.delPie();
            	var mark="";
            	//3级别以下省;4,5,6级别市 ; 7以上行政区
            	if(this.map.getLevel()<=3){
            		mark="province"
            	}else if(this.map.getLevel()>=4 && this.map.getLevel()<=6){
            		mark="city"
            	}else if(this.map.getLevel()>=7){
            		mark="distinct"
            	}
            	
            	mark="city";//只取市区!!!!!
            	
            	ioc.map.ClusterMapLevel = this.map.getLevel() ; 
            	if(mark == ioc.map.ClusterDimension){// 同一个维度时重新加载 
                	this.addPie(0);
            	}else{// 非同一个维度时重新查询加载 
            		  
            		if(mark == 'distinct' ){  
            			ioc.map.ClusterDimension = mark;
                    	this.addPie(1);
                	}else if(mark == 'city'){ 
                		ioc.map.ClusterDimension = mark;
                    	this.addPie(2);
                	}else if(mark == 'province'){ 
                		ioc.map.ClusterDimension = mark;
                    	this.addPie(3);
                	}
            		ioc.map.ClusterDimension = mark;
            	}

            }else{//拖动 不需操作
            	
            	
            }
        },
        
        addPie:function(flag){
        	var temp = this;
        	this.initCluster(null,null,flag,temp);
        },
        
        getLayer:function(){
        	if(!this._toolTipLayer){
        		this._toolTipLayer=dojo.toDom("<div style='position: absolute;z-index:20;'></div>");
        	}
        	dojo.place(this._toolTipLayer,this.map.root);
        	return this._toolTipLayer;
        },
        
        delPie:function(){
        	 for(var d=0;d<50;d++){ //TODO 这里删除一次不知为何节点有漏,50为多次删除
             	var canvasNodes = document.getElementsByTagName('canvas');
             	 for(var g=0;g<canvasNodes.length;g++){
             	  var aNode = document.getElementsByTagName('canvas')[g].parentNode;
             		 if(aNode != undefined){
             		  var bNode = aNode.parentNode
             		      if(bNode != undefined){
             			  if(bNode.attributes[0].nodeValue=="stat2"){
             			      //删除
             			       var pNode = document.getElementsByTagName('canvas')[g].parentNode.parentNode.parentNode;
             				for (var i = 0;i<pNode.childNodes.length;i++){
             				    pNode.removeChild(pNode.childNodes[i]);
             				}
             				break;
             			  }
             		      }
             		 }
             	 }}
          },
        
        startup:function(){
            this.inherited(arguments);
        },
         
        onClose:function(){
        	this.inherited(arguments);
        }
     });
});